"""
# -*- coding: utf-8 -*-
# @Time    : 2023/10/16 21:54
# @Author  : 王摇摆
# @FileName: test-gpu.py
# @Software: PyCharm
# @Blog    ：https://blog.csdn.net/weixin_44943389?type=blog
"""
# 导入必要的库
import pandas as pd
from tensorflow.keras.layers import SimpleRNN, Dense
from tensorflow.keras.models import Sequential
import tensorflow as tf

# 检查 GPU 是否可用
physical_devices = tf.config.list_physical_devices('GPU')
if physical_devices:
    tf.config.experimental.set_memory_growth(physical_devices[0], True)
    print("[INFO] GPU found and configured.")
else:
    print("[INFO] No GPU found. Running on CPU.")

# 1. 读取数据
data = pd.read_csv('../dataset/train.csv')
test_data = pd.read_csv('../dataset/test.csv')
print('[1. 数据集加载完毕]')

# 2. 分离特征和目标变量
X = data.drop(columns=['id', 'target'])
y = data['target']

test_X = test_data.drop(columns='id')
print('[2. 数据集预处理完成]')

# 3. 初始化并构建RNN模型
# 初始化并构建RNN模型
with tf.device('/GPU:0'):  # 指定在第一个 GPU 上运行
    model = Sequential([
        SimpleRNN(64, input_shape=(1, X.shape[1]), activation='relu'),  # 添加一个SimpleRNN层
        Dense(1, activation='sigmoid')
    ])
    model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

# 4. 将数据整理成适合RNN的格式
X = X.values.reshape(-1, 1, X.shape[1])
test_X = test_X.values.reshape(-1, 1, test_X.shape[1])

# 5. 训练RNN模型
import matplotlib.pyplot as plt

# 训练RNN模型
with tf.device('/GPU:0'):  # 指定在第一个 GPU 上运行
    history = model.fit(X, y, epochs=5, batch_size=32)

# 获取训练过程中的损失值和准确率
loss = history.history['loss']
accuracy = history.history['accuracy']

# 绘制损失值和准确率的变化曲线
epochs = range(1, len(loss) + 1)

plt.figure(figsize=(12, 4))

# 绘制损失值曲线
plt.subplot(1, 2, 1)
plt.plot(epochs, loss, 'b-', label='Training Loss')
plt.title('Training Loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()

# 绘制准确率曲线
plt.subplot(1, 2, 2)
plt.plot(epochs, accuracy, 'b-', label='Training Accuracy')
plt.title('Training Accuracy')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend()

plt.tight_layout()
plt.show()

# 6. 预测
# y_pred = model.predict(test_X)
# y_pred = (y_pred > 0.5).astype(int).reshape(-1)

# # 7. 预测结果输出
# pd.DataFrame({'id': test_data['id'], 'target': y_pred}).to_csv('../result/RNN.csv', index=None)
# print('[3. 预测结果已输出为CSV文件]')

